*===============================================================================

global graphoption graphregion(color(white)) ylabel(, angle(0))

global tabvarlist ///
	age_borrower advtype_1 ///
	///
	gross_income  employment_1 employment_4 ///
	///
	purchaseprice deposit_final equity loan_val interest mortgage_term ///
	fix2 fix_other ///
	///
	LTV combined_LTV LTI combined_LTI PTI PTInet 
	
*===============================================================================

program add_parenthesis
	syntax varlist
	foreach x in `varlist' {	
		capture tostring `x', replace usedisplayformat force
		replace `x' = "(" + `x' + ")"
	}
end

program latexTable
	unab allVar: _all
	token `allVar'
	foreach v of varlist `allVar' {
		if "`1'" != "`*'" {
			capture confirm string variable `v'
			if _rc {
				tostring `v', replace force usedisplayformat  
				replace `v' = "" if `v' == "."
			}
			replace `v' = `v' + " &"
		}
		else {
			capture confirm string variable `v'
			if _rc {
				tostring `v', replace force usedisplayformat
				replace `v' = "" if `v' == "."
			}	  
			replace `v' = `v' + " \\"
		}
		macro shift
	}
end

program table_diff_format
	replace _varname =  "\textsc{\quad Gross income (\pounds .000)}" if _varname == "gross_income"
	replace _varname = "\textsc{\quad Age (Years)}" if _varname ==  "age_borrower"

	if inlist("`1'", "ftb", "hm") {
		drop if inlist(_varname, "advtype_1", "advtype_2")
	}
	else {
		replace _varname = 	"\textsc{\quad First time buyers (\%)}" if _varname == "advtype_1" 
		replace _varname = 	"\textsc{\quad Home movers (\%)}"  	if _varname == "advtype_2"
	}
		
	replace _varname = "\textsc{\quad Employed (\%)}" if _varname ==  "employment_1"
	replace _varname = "\textsc{\quad Other (\%)}" if _varname ==  "employment_2"
	replace _varname = "\textsc{\quad Retired (\%)}" if _varname ==  "employment_3"
	replace _varname = "\textsc{\quad Self-employed (\%)}" if _varname ==  "employment_4"
	replace _varname = "\textsc{\quad Property value (\pounds .000)}" if _varname ==  "purchaseprice"
	replace _varname = "\textsc{\quad Down payment (\pounds .000)}" if _varname ==  "deposit_final"
	replace _varname = "\textsc{\quad Equity loan (\pounds .000)}" if _varname ==  "equity"
	replace _varname = "\textsc{\quad Mortgage value (\pounds .000)}" if _varname ==  "loan_val"
	replace _varname = "\textsc{\quad Interest Rate (\%)}" if _varname ==  "interest"
	replace _varname = "\textsc{\quad Maturity (Years)}" if _varname ==  "mortgage_term"
	replace _varname = "\textsc{\quad 2-year fixed (\%)}" if _varname ==  "fix2"
	replace _varname = "\textsc{\quad Other fixed (\%)}" if _varname ==  "fix_other"
	replace _varname = "\textsc{\quad LTV}" if _varname ==  "LTV"
	replace _varname = "\textsc{\quad Combined LTV}" if _varname ==  "combined_LTV"
	replace _varname = "\textsc{\quad LTI}" if _varname ==  "LTI"
	replace _varname = "\textsc{\quad Combined LTI}" if _varname ==  "combined_LTI"
	replace _varname = "\textsc{\quad Downpayment-To-Gross income (\%)}" if _varname ==  "DTI_final"
	replace _varname = "\textsc{\quad Payment-To-Gross income (\%)}" if _varname ==  "PTI"
	replace _varname = "\textsc{\quad Payment-To-Net income (\%)}" if _varname ==  "PTInet"
	replace _varname = "\textsc{\quad House-To-Gross income}" if _varname ==  "HTI"
	replace _varname = "\textsc{\quad Exposure (\pounds .000)}" 	if _varname ==  "exposure1"
	replace _varname = "\textsc{\quad Exposure-To-Gross income}" if _varname ==  "exposure2"
	
	replace _varname = "\textsc{\quad Break-even hp appreciation (\%)}" if _varname ==  "bkhp_mortgage"
	
	replace _varname = "\textsc{\quad Intermediated sales (\%)}" 			if _varname ==  "broker"
	replace _varname = "\textsc{\quad House price to Income}" 				if _varname ==  "ons_affordability_lag1"
	replace _varname = "\textsc{\quad Past 2 years hp appreciation (\%)}" 	if _varname ==  "ons_houseprice_delta2"
	replace _varname = "\textsc{\quad Past 1 year hp appreciation (\%)}" 	if _varname ==  "ons_houseprice_delta1"
	replace _varname = "\textsc{\quad Next year hp expectations (\%)}" 		if _varname ==  "hpexp_mean"
	
	replace _varname = "\textsc{\quad Housing consumption to income}" 		if _varname ==  "CTI"
	replace _varname = "\textsc{\quad Housing exposure to income}" 			if _varname ==  "ETI"
end


program collapse_vars
	collapse ${tabvarlist}, by(`1')
	xpose, varname clear
	order _varname
end					


program collapse_vars_count
	collapse (count) ${tabvarlist}, by(`1')
	xpose, varname clear
	order _varname
end


program collapse_vars_sd
	collapse (sd) ${tabvarlist}, by(`1')
	xpose, varname clear
	order _varname
end


program prepare_ttest_result
	tostring diff, replace usedisplayformat force
	replace diff = cond(pvalue < 0.01, diff + "$^{***}$", ///
		cond(pvalue < 0.05, diff + "$^{**}$", /// 
		cond(pvalue < 0.1, diff + "$^{*}$", diff))) 
	drop pvalue
end


program table_diff
	rename v1 v1_sd
	rename v2 v2_sd

	gen sort_order = _n
	merge 1:1 _varname using "${tabledir}\descriptive_mean${tabsample}", nogen
	merge 1:1 _varname using "${tabledir}\descriptive_count${tabsample}", nogen
	sort sort_order	// because merge changes sort order

	drop if _varname == "`1'"

	if "`1'" == "repay" {	
		gen diff = v1 - v2
	}
	else { 
		gen diff = v2 - v1
	}	
	
	// ttest
	gen pvalue = .

	local n = _N
	forvalues i = 1/`n' {
		forvalues j = 1/2 {
			sum v`j' in `i', meanonly
			local meanv`j' = r(mean)
			
			sum v`j'_sd in `i', meanonly
			local sdv`j' = r(mean)
			
			sum v`j'_count in `i', meanonly
			local count`j' = r(mean)
		}
		if "`1'" == "repay" {
			ttesti `count1' `meanv1' `sdv1' `count2' `meanv2' `sdv2'
		}
		else {
			ttesti `count2' `meanv2' `sdv2' `count1' `meanv1' `sdv1'
		}
		replace pvalue = r(p) in `i'
	}

	// format the table	
	if "`1'" == "post" {
		keep _varname v2 v2_sd v1 v1_sd pvalue diff
		order _varname v1 v1_sd v2 v2_sd pvalue diff
	}
	else if "`1'" == "repay" {
		keep _varname v0 v2 v2_sd v1 v1_sd pvalue diff
		order _varname v0 v1 v1_sd v2 v2_sd pvalue diff
	}
	else {
		keep _varname v2 v2_sd v1 v1_sd pvalue diff
		order _varname v2 v2_sd v1 v1_sd pvalue diff
	}
	format v* diff %4.2fc
end

program table_diff_last_row
	use "${tabledir}\descriptive_count${tabsample}", replace
	keep in 2
	replace _varname = "\$N\$"
	forvalues i = 1/2 {
		gen space`i' = ""
	}
	gen totsum = v2 + v1
	if "`1'" == "post" {
		order _varname v1 space1 v2 space2 totsum
	}
	else {
		order _varname v2 space2 v1 space1 totsum
	}
	format v2 v1 totsum %7.0fc
end


program prepare_vars_remortgage
	gen month = round( (next_date - date) / 30 )

	gen lb 	= loan_final * (1+interest00/12)^month ///
			-  payment * (((1+interest00/12)^month - 1)/(interest00/12) ) 
end